const { db, sqlExec } = require('../db/mysql57');

const taskDao = {
    /*
     * 新增任务
     */
    async addTask(uid, name, description, count) {
        let sql = `INSERT INTO Task(uid, name, description, count) VALUES (?, ?, ?, ?)`;
        let data = [ uid, name, description, count ];
        return sqlExec(sql, data);
    },
    /*
     * 删除任务
     */
    async deleteTask(uid, taskId) {
        let sql = `delete from Task where uid = ? and id = ?`;
        let data = [ uid, taskId ];
        return sqlExec(sql, data);
    },
    /*
     * 修改任务状态为已完成
    */
    async setTaskComplete(uid, taskId) {
        let sql = `insert into TaskSignIn(taskId) (
            select ? where (
                select count(1) from TaskSignIn
                where taskId = ? and DATE(time) = CURRENT_DATE()
            ) = 0 and (
                select count(1) from Task
                where uid = ? and id = ?
            ) = 1
        )`;
        let data = [ taskId, taskId, uid, taskId ];
        return sqlExec(sql, data);
    },
    /*
     * 获取任务列表
     */
    async getTaskList(uid) {
        let sql = `select
                id,
                name as taskName,
                description as taskDescription,
                (
                    select count(1) from TaskSignIn
                    where taskId = Task.id and DATE(time) = CURRENT_DATE()
                ) as completed,
                count,
                (
                    select count(1) from TaskSignIn
                    where taskId = Task.id
                ) as checked
            from Task
            where uid = ?`;
        let data = [ uid ];
        return sqlExec(sql, data);
    },
    /*
     * 获取任务签到列表
     */
    async getAllTaskCheckin(uid, page) {
        let sql = `select
                ts.id as id,
                u.username as username,
                u.id as uid,
                u.openid as openid,
                t.name as taskName,
                DATE_FORMAT(ts.time, '%Y-%m-%d %H:%i:%s') as time
            from TaskSignIn as ts
            left join Task as t on ts.taskId = t.id
            left join User as u on t.uid = u.id
            order by ts.time desc
            limit ?, 50`;
        let data = [ (page-1) * 50 ];
        return sqlExec(sql, data);
    }
}


module.exports = taskDao;